#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
C服务器测试脚本: G服务器注册场景 (场景1.1-1.5)
测试G服务器注册到C服务器的各种情况
"""

import requests
import json
import time
import sys
import os
from typing import Dict, Any

# 添加项目根目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), '../../1-gateway/02-api-gateway'))

class GRegisterTester:
    """G服务器注册测试类"""
    
    def __init__(self):
        self.gateway_url = "https://www.gongjuxiang.work"
        self.webhook_url = f"{self.gateway_url}/webhook/register"
        self.backend_servers_file = "../../1-gateway/02-api-gateway/backend_servers.json"
        self.correct_secret = "gpu-server-register-to-api-gateway-2024"
        self.wrong_secret = "wrong-password"
        
    def load_backend_servers(self) -> list:
        """加载backend_servers.json"""
        try:
            with open(self.backend_servers_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"❌ 加载backend_servers.json失败: {e}")
            return []
    
    def save_backend_servers(self, servers: list):
        """保存backend_servers.json"""
        try:
            with open(self.backend_servers_file, 'w', encoding='utf-8') as f:
                json.dump(servers, f, indent=2, ensure_ascii=False)
            print(f"✅ backend_servers.json已保存: {len(servers)}个服务器")
        except Exception as e:
            print(f"❌ 保存backend_servers.json失败: {e}")
    
    def clear_backend_servers(self):
        """清空backend_servers.json (场景1.1准备)"""
        self.save_backend_servers([])
        print("🧹 已清空backend_servers.json")
    
    def register_g_server(self, data: Dict[str, Any]) -> tuple[bool, str]:
        """发送注册请求到C服务器"""
        try:
            response = requests.post(self.webhook_url, json=data, timeout=10)
            if response.status_code == 200:
                result = response.json()
                return True, result.get('server_id', '')
            else:
                print(f"❌ 注册失败: {response.status_code} - {response.text}")
                return False, ""
        except Exception as e:
            print(f"❌ 注册请求异常: {e}")
            return False, ""
    
    def test_scenario_1_1(self):
        """场景1.1: G首次注册（backend_servers.json为空）"""
        print("\n" + "="*60)
        print("🧪 场景1.1: G首次注册（backend_servers.json为空）")
        print("="*60)
        
        # 准备：清空服务器列表
        self.clear_backend_servers()
        
        # 模拟G服务器注册数据
        register_data = {
            "internal_ip": "10.5.0.191",
            "public_ip": "140.143.155.42", 
            "region": "ap-beijing",
            "port": 5800,
            "secret": self.correct_secret
        }
        
        print(f"📤 发送注册请求: {register_data}")
        
        # 发送注册请求
        success, server_id = self.register_g_server(register_data)
        
        if success:
            print(f"✅ 注册成功，server_id: {server_id}")
            
            # 验证backend_servers.json
            servers = self.load_backend_servers()
            if len(servers) == 1:
                server = servers[0]
                print(f"✅ backend_servers.json验证通过:")
                print(f"   - server_id: {server['server_id']}")
                print(f"   - internal_ip: {server['internal_ip']}")
                print(f"   - region: {server['region']}")
                print(f"   - port: {server['port']}")
                print(f"   - is_healthy: {server['is_healthy']}")
                
                if (server['internal_ip'] == "10.5.0.191" and 
                    server['region'] == "ap-beijing" and 
                    server['port'] == 5800):
                    print("✅ 场景1.1测试通过")
                    return True
                else:
                    print("❌ 服务器数据验证失败")
                    return False
            else:
                print(f"❌ backend_servers.json服务器数量错误: {len(servers)}")
                return False
        else:
            print("❌ 注册失败")
            return False
    
    def test_scenario_1_2(self):
        """场景1.2: G重新注册（已有旧记录）"""
        print("\n" + "="*60)
        print("🧪 场景1.2: G重新注册（已有旧记录）")
        print("="*60)
        
        # 准备：确保已有服务器记录
        servers = self.load_backend_servers()
        if len(servers) == 0:
            print("⚠️ 没有现有服务器记录，先执行场景1.1")
            if not self.test_scenario_1_1():
                return False
        
        # 记录原有server_id
        original_servers = self.load_backend_servers()
        original_server_id = original_servers[0]['server_id'] if original_servers else None
        print(f"📋 原有server_id: {original_server_id}")
        
        # 模拟G服务器重新注册（相同IP+端口）
        register_data = {
            "internal_ip": "10.5.0.191",
            "public_ip": "140.143.155.42",
            "region": "ap-beijing", 
            "port": 5800,
            "secret": self.correct_secret
        }
        
        print(f"📤 发送重新注册请求: {register_data}")
        
        # 发送重新注册请求
        success, server_id = self.register_g_server(register_data)
        
        if success:
            print(f"✅ 重新注册成功，server_id: {server_id}")
            
            # 验证server_id保持不变
            if server_id == original_server_id:
                print("✅ server_id保持不变，场景1.2测试通过")
                
                # 验证服务器状态已更新
                servers = self.load_backend_servers()
                if servers and servers[0]['is_healthy']:
                    print("✅ 服务器状态已更新为健康")
                    return True
                else:
                    print("❌ 服务器状态更新失败")
                    return False
            else:
                print(f"❌ server_id发生变化: {original_server_id} -> {server_id}")
                return False
        else:
            print("❌ 重新注册失败")
            return False
    
    def test_scenario_1_3(self):
        """场景1.3: 多个G同时注册"""
        print("\n" + "="*60)
        print("🧪 场景1.3: 多个G同时注册")
        print("="*60)
        
        # 准备：清空服务器列表
        self.clear_backend_servers()
        
        # 模拟多个G服务器同时注册
        g_servers = [
            {
                "internal_ip": "10.5.0.191",
                "public_ip": "140.143.155.42",
                "region": "ap-beijing",
                "port": 5800,
                "secret": self.correct_secret,
                "name": "G1"
            },
            {
                "internal_ip": "10.6.0.123", 
                "public_ip": "140.143.155.43",
                "region": "ap-beijing",
                "port": 5800,
                "secret": self.correct_secret,
                "name": "G2"
            }
        ]
        
        print("📤 模拟多G服务器同时注册...")
        
        registered_servers = []
        for g_server in g_servers:
            print(f"   - {g_server['name']}: {g_server['internal_ip']}")
            success, server_id = self.register_g_server(g_server)
            if success:
                registered_servers.append((g_server['name'], server_id))
                print(f"   ✅ {g_server['name']} 注册成功: {server_id}")
            else:
                print(f"   ❌ {g_server['name']} 注册失败")
        
        # 验证结果
        if len(registered_servers) == len(g_servers):
            print("✅ 所有G服务器注册成功")
            
            # 验证backend_servers.json
            servers = self.load_backend_servers()
            if len(servers) == 2:
                print("✅ backend_servers.json包含2个服务器")
                for server in servers:
                    print(f"   - {server['server_id']}: {server['internal_ip']}")
                print("✅ 场景1.3测试通过")
                return True
            else:
                print(f"❌ backend_servers.json服务器数量错误: {len(servers)}")
                return False
        else:
            print(f"❌ 部分G服务器注册失败: {len(registered_servers)}/{len(g_servers)}")
            return False
    
    def test_scenario_1_4(self):
        """场景1.4: G注册失败（密钥错误）"""
        print("\n" + "="*60)
        print("🧪 场景1.4: G注册失败（密钥错误）")
        print("="*60)
        
        # 记录注册前的服务器数量
        servers_before = self.load_backend_servers()
        count_before = len(servers_before)
        print(f"📋 注册前服务器数量: {count_before}")
        
        # 模拟G服务器使用错误密钥注册
        register_data = {
            "internal_ip": "10.5.0.191",
            "public_ip": "140.143.155.42",
            "region": "ap-beijing",
            "port": 5800,
            "secret": self.wrong_secret  # 错误的密钥
        }
        
        print(f"📤 发送错误密钥注册请求: {register_data}")
        
        # 发送注册请求
        success, server_id = self.register_g_server(register_data)
        
        # 验证注册失败
        if not success:
            print("✅ 注册失败（符合预期）")
            
            # 验证backend_servers.json没有变化
            servers_after = self.load_backend_servers()
            count_after = len(servers_after)
            
            if count_after == count_before:
                print("✅ backend_servers.json没有变化")
                print("✅ 场景1.4测试通过")
                return True
            else:
                print(f"❌ backend_servers.json发生变化: {count_before} -> {count_after}")
                return False
        else:
            print(f"❌ 注册成功（不符合预期）: {server_id}")
            return False
    
    def test_scenario_1_5(self):
        """场景1.5: G注册失败（网络不通）"""
        print("\n" + "="*60)
        print("🧪 场景1.5: G注册失败（网络不通）")
        print("="*60)
        
        # 使用错误的网关URL模拟网络不通
        wrong_webhook_url = "https://wrong-domain.com/webhook/register"
        
        register_data = {
            "internal_ip": "10.5.0.191",
            "public_ip": "140.143.155.42",
            "region": "ap-beijing",
            "port": 5800,
            "secret": self.correct_secret
        }
        
        print(f"📤 发送到错误URL: {wrong_webhook_url}")
        print(f"📤 注册数据: {register_data}")
        
        try:
            response = requests.post(wrong_webhook_url, json=register_data, timeout=5)
            print(f"❌ 意外成功: {response.status_code}")
            return False
        except requests.exceptions.ConnectionError:
            print("✅ 连接失败（符合预期）")
            print("✅ 场景1.5测试通过")
            return True
        except requests.exceptions.Timeout:
            print("✅ 超时失败（符合预期）")
            print("✅ 场景1.5测试通过")
            return True
        except Exception as e:
            print(f"✅ 网络错误（符合预期）: {e}")
            print("✅ 场景1.5测试通过")
            return True
    
    def run_all_tests(self):
        """运行所有注册场景测试"""
        print("🚀 开始G服务器注册场景测试")
        print(f"🌐 网关URL: {self.gateway_url}")
        print(f"📁 backend_servers.json路径: {self.backend_servers_file}")
        
        tests = [
            ("场景1.1", self.test_scenario_1_1),
            ("场景1.2", self.test_scenario_1_2), 
            ("场景1.3", self.test_scenario_1_3),
            ("场景1.4", self.test_scenario_1_4),
            ("场景1.5", self.test_scenario_1_5)
        ]
        
        results = []
        for test_name, test_func in tests:
            try:
                result = test_func()
                results.append((test_name, result))
                time.sleep(1)  # 测试间隔
            except Exception as e:
                print(f"❌ {test_name}测试异常: {e}")
                results.append((test_name, False))
        
        # 输出测试结果
        print("\n" + "="*60)
        print("📊 测试结果汇总")
        print("="*60)
        
        passed = 0
        for test_name, result in results:
            status = "✅ 通过" if result else "❌ 失败"
            print(f"{test_name}: {status}")
            if result:
                passed += 1
        
        print(f"\n📈 总体结果: {passed}/{len(results)} 个测试通过")
        
        if passed == len(results):
            print("🎉 所有G服务器注册场景测试通过！")
            return True
        else:
            print("⚠️ 部分测试失败，请检查相关配置")
            return False

def main():
    """主函数"""
    print("🧪 C服务器测试脚本: G服务器注册场景")
    print("测试场景: 1.1-1.5")
    print("-" * 60)
    
    tester = GRegisterTester()
    success = tester.run_all_tests()
    
    if success:
        print("\n✅ 所有测试完成，结果正常")
        sys.exit(0)
    else:
        print("\n❌ 测试失败，请检查配置")
        sys.exit(1)

if __name__ == "__main__":
    main()
